#!/usr/bin/env python

# Need subprocess to call exec commands

import subprocess,re
from flask import Flask, session, redirect, url_for, escape, request
import threading

# Function to run command as argument

def cmd(c):

   cc = subprocess.Popen(c.split(),stdout=subprocess.PIPE)
   return cc.stdout.readlines()

# List all LXC

def lxccontrol(ctl,*other):

  if ctl == "list":

    lf = []
    for _ in cmd("/usr/bin/lxc-ls --fancy"):
      lf.append(_+"<br>")
    return ''.join(lf)

# Stop LXC

  elif ctl == "stop":

    machine = other[0] 

    if not re.search("^\w+$",machine):
      return "Input Error"
    else:
      t = threading.Thread(target=cmd,args=["/usr/bin/lxc-stop -n {0} -q".format(machine)])
      t.start()
      return "lxc stopped"

# Destroy LXC

  elif ctl == "destroy":

    machine = other[0]

    if not re.search("^\w+$",machine):
      return "Input Error"
    else:
      t = threading.Thread(target=cmd,args=["/usr/bin/lxc-destroy -n {0} -q".format(machine)])
      t.start()
      return "lxc destroyed"

# Create LXC

  elif ctl == "create":
 
    machine = other[0]
    types = other[1]

    if not re.search("^\w+$",machine):
      return "Input Error"

    elif not re.search("^\w+$",types):
      return "Input Error"
   
    else:
      # thread to not tie it up
      t = threading.Thread(target=cmd,args=["/usr/bin/lxc-create -t {0} -n {1} -q".format(types,machine)])
      t.start()
      return "lxc created"

# Start LXC

  elif ctl == "start":

    machine = other[0]

    if not re.search("^\w+$",machine):
      return "Input Error"
    else:
      t = threading.Thread(target=cmd,args=["/usr/bin/lxc-start -n {0} -q -d".format(machine)])
      t.start()
      return "lxc started"

# Freeze LXC

  elif ctl == "freeze":

    machine = other[0]

    if not re.search("^\w+$",machine):
      return "Input Error"
    else:
      t = threading.Thread(target=cmd,args=["/usr/bin/lxc-freeze -n {0} -q".format(machine)])
      t.start()
      return "lxc freezed"
 
# Unfreeze LXC

  elif ctl == "unfreeze":

    machine = other[0]

    if not re.search("^\w+$",machine):
      return "Input Error"
    else:
      t = threading.Thread(target=cmd,args=["/usr/bin/lxc-unfreeze -n {0} -q".format(machine)])
      t.start()
      return "lxc unfreezed"

# Snapshot LXC

  elif ctl == "snapshot":

    machine = other[0]

    if not re.search("^\w+$",machine):
      return "Input Error"
    else:

      # thread to not tie it up
      t = threading.Thread(target=cmd,args=["/usr/bin/lxc-snapshot -n {0} -q".format(machine)])
      t.start()

      return "lxc snapshoted"

  else: 
    pass
